# app/api/kb/routes.py

from typing import List, Dict, Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from app.core.knowledge_base_manager import get_kb_manager
from app.core.logging import get_logger

logger = get_logger(__name__)

router = APIRouter()

class CreateKnowledgeBaseRequest(BaseModel):
    """创建知识库请求模型"""
    name: str
    description: str = ""

class KnowledgeBaseResponse(BaseModel):
    """知识库响应模型"""
    name: str
    description: str
    file_count: int
    created_time: str
    last_updated: str
    text_collection: str
    image_collection: str

@router.post("/create", response_model=KnowledgeBaseResponse, summary="创建知识库")
async def create_knowledge_base(request: CreateKnowledgeBaseRequest):
    """创建新的知识库"""
    logger.info(f"收到创建知识库请求: {request.name}")
    
    try:
        kb_manager = get_kb_manager()
        success = kb_manager.create_knowledge_base(request.name, request.description)
        
        if not success:
            raise HTTPException(status_code=400, detail=f"知识库 {request.name} 已存在或创建失败")
        
        # 获取创建的知识库信息
        kb_info = kb_manager.get_knowledge_base(request.name)
        if not kb_info:
            raise HTTPException(status_code=500, detail="知识库创建成功但无法获取信息")
        
        logger.info(f"知识库 {request.name} 创建成功")
        return KnowledgeBaseResponse(**kb_info)
        
    except Exception as e:
        logger.error(f"创建知识库失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/list", response_model=List[KnowledgeBaseResponse], summary="列出所有知识库")
async def list_knowledge_bases():
    """列出所有知识库"""
    logger.info("收到列出知识库请求")
    
    try:
        kb_manager = get_kb_manager()
        kb_list = kb_manager.list_knowledge_bases()
        
        logger.info(f"找到 {len(kb_list)} 个知识库")
        return [KnowledgeBaseResponse(**kb) for kb in kb_list]
        
    except Exception as e:
        logger.error(f"列出知识库失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{kb_name}", response_model=KnowledgeBaseResponse, summary="获取知识库信息")
async def get_knowledge_base(kb_name: str):
    """获取指定知识库的信息"""
    logger.info(f"收到获取知识库信息请求: {kb_name}")
    
    try:
        kb_manager = get_kb_manager()
        kb_info = kb_manager.get_knowledge_base(kb_name)
        
        if not kb_info:
            raise HTTPException(status_code=404, detail=f"知识库 {kb_name} 不存在")
        
        return KnowledgeBaseResponse(**kb_info)
        
    except Exception as e:
        logger.error(f"获取知识库信息失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{kb_name}", summary="删除知识库")
async def delete_knowledge_base(kb_name: str):
    """删除指定的知识库"""
    logger.info(f"收到删除知识库请求: {kb_name}")
    
    try:
        kb_manager = get_kb_manager()
        success = kb_manager.delete_knowledge_base(kb_name)
        
        if not success:
            raise HTTPException(status_code=404, detail=f"知识库 {kb_name} 不存在或删除失败")
        
        logger.info(f"知识库 {kb_name} 删除成功")
        return {"message": f"知识库 {kb_name} 删除成功"}
        
    except Exception as e:
        logger.error(f"删除知识库失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{kb_name}/stats", summary="获取知识库统计信息")
async def get_knowledge_base_stats(kb_name: str):
    """获取知识库的统计信息"""
    logger.info(f"收到获取知识库统计信息请求: {kb_name}")
    
    try:
        kb_manager = get_kb_manager()
        kb_info = kb_manager.get_knowledge_base(kb_name)
        
        if not kb_info:
            raise HTTPException(status_code=404, detail=f"知识库 {kb_name} 不存在")
        
        # 获取Milvus集合统计信息
        from pymilvus import utility, Collection
        
        collection_names = kb_manager.get_collection_names(kb_name)
        text_collection_name = collection_names["text_collection"]
        image_collection_name = collection_names["image_collection"]
        
        stats = {
            "name": kb_name,
            "description": kb_info["description"],
            "file_count": kb_info["file_count"],
            "created_time": kb_info["created_time"],
            "last_updated": kb_info["last_updated"],
            "text_entities": 0,
            "image_entities": 0
        }
        
        # 获取文本集合统计
        if utility.has_collection(text_collection_name):
            text_collection = Collection(text_collection_name)
            stats["text_entities"] = text_collection.num_entities
        
        # 获取图片集合统计
        if utility.has_collection(image_collection_name):
            image_collection = Collection(image_collection_name)
            stats["image_entities"] = image_collection.num_entities
        
        return stats
        
    except Exception as e:
        logger.error(f"获取知识库统计信息失败: {e}")
        raise HTTPException(status_code=500, detail=str(e)) 